#pragma once
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>

#include "Log.hpp"
#include "InetAddr.hpp"


// 套接字命名空间
namespace socket_ns
{
    using namespace log_ns;

    class Socket;
    using SockSptr = std::shared_ptr<Socket>;
    
    enum
    {
        SOCKET_ERROR = 1,
        BAND_ERROR,
        LISTEN_ERROR
    };

    const static int gblcklog = 8;

    class Socket
    {
    public:
        // 模板类方法
        virtual void CreateSocketOrDie() = 0;
        virtual void CreateBindOrDie(uint16_t port) = 0;
        virtual void CreateListenOrDie(int blcklog = gblcklog) = 0;
        virtual SockSptr Accepter(InetAddr *cliaddr) = 0;
        virtual bool Connector(const std::string &peerip,uint16_t peerport)=0;
        virtual int Sockfd()=0;
        virtual void Close()=0;
        
        virtual ssize_t Recv(std::string *out)=0;
        virtual int Send(const std::string &in)=0;

    public:
        void BuildListenSocket(uint16_t port)
        {
            CreateSocketOrDie();
            CreateBindOrDie(port);
            CreateListenOrDie();
        }

        bool BuildClientSocket(const std::string &peerip,uint16_t peerport)
        {
            CreateSocketOrDie();
            return Connector(peerip,peerport);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
        {
        }

        TcpSocket(int sockfd) : _sockfd(sockfd)
        {
        }

        ~TcpSocket()
        {

        }

        void CreateSocketOrDie() override
        {
            // 创建
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                exit(SOCKET_ERROR);
                LOG(FATAL, "socket create error\n");
            }
            LOG(INFO, "socket create sussess,sockfd: %d\n", _sockfd); // 3
        }

        void CreateBindOrDie(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));

            local.sin_family = AF_INET;
            local.sin_port = htons(port); // 网络序列
            local.sin_addr.s_addr = INADDR_ANY;
            // 绑定：sockfd 和 socket addr
            if (::bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(BAND_ERROR);
            }
            LOG(INFO, "bind sussess,sockfd: %d\n", _sockfd); // 3
        }

        void CreateListenOrDie(int blcklog) override
        {
            // 设置监听状态 listen
            if (::listen(_sockfd, blcklog) < 0)
            {
                LOG(FATAL, "listen error\n");
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "listen success\n");
        }

        SockSptr Accepter(InetAddr *cliaddr) override
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 获取新连接
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                // 获取连接失败
                LOG(WARING, "accept error\n");
                return nullptr;
            }
            *cliaddr = InetAddr(client);
            LOG(INFO, "get a new link,client info: %s, sockfd is: %d\n", cliaddr->AddrStr().c_str(), sockfd); // 4
            return std::make_shared<TcpSocket>(sockfd);
        }

        bool Connector(const std::string &peerip,uint16_t peerport) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            // server.sin_addr.s_addr
            ::inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);

            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                std::cerr << "connect socket error" << std::endl;
                return false;
            }
            return true;
        }

        int Sockfd() override
        {
            return _sockfd;
        }

        void Close() override
        {
            if(_sockfd>0)
            {
                ::close(_sockfd);
            }
        }

        ssize_t Recv(std::string *out) override
        {
            char inbuffer[4096];
            ssize_t n=::recv(_sockfd,inbuffer,sizeof(inbuffer)-1,0);
            if(n>0)
            {
                inbuffer[n]=0;
                *out+=inbuffer;
            }
            return n;
        }

        int Send(const std::string &in) override
        {
            return ::send(_sockfd,in.c_str(),in.size(),0);
        }

    private:
        int _sockfd; // 可以是listensock 可以是普通sockfd
    };

    // class UdpSocket: public Socket
    // {};
    // Socket *sock=new TcpSocket();
    // sock->BuildListenSocket();

};